/*给你一个链表的头节点 head 和一个整数 val ，请你删除链表中所有满足 Node.val == val 的节点，并返回新的头节点 。
*
* 输入：head = [1,2,6,3,4,5,6], val = 6
* 输出：[1,2,3,4,5]
* */

package Leetcode;

public class leetcode203 {

    public static void main(String[] args) {

        leetcode203 obj = new leetcode203();
        ListNode_203 head = new ListNode_203(1);
        head.add(2);
        head.add(6);
        head.add(3);
        head.add(4);
        head.add(5);
        head.add(6);
        int val = 6;
        ListNode_203 node = obj.removeElements(head, val);
        while (node != null){
            System.out.println(node.val);
            node = node.next;
        }
    }

    public ListNode_203 removeElements(ListNode_203 head, int val){
        if(head == null){
            return head;
        }
        //定义一个指向head的指针
        ListNode_203 pre = new ListNode_203(0);
        pre.next = head;

        //定义指向pre的指针，后续操作中进行移动
        ListNode_203 p = pre;
        ListNode_203 cur = head;
        while(p.next != null){

            if(cur.val != val){
                p = cur;
                cur = cur.next;
            }else{
                p.next = cur.next;
                cur = cur.next;
            }
        }
        return pre.next;
    }
}

class ListNode_203{
    int val;
    ListNode_203 next;
    ListNode_203(int x){
        val = x;
        next = null;
    }

    public void add(int x){
        ListNode_203 newnode = new ListNode_203(x);
        if (this.next == null){
            this.next = newnode;
        }else {
            this.next.add(x);
        }
    }
}
